<?php

require_once 'Basic.php';

class FormFieldDate extends FormFieldType {
  
  private static $leapYearsMonths = array(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  private static $nonLeapYearsMonths = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  private static $monthNames = array("", "Janeiro", "Fevereiro", "Mar&ccedil;o", "Abril", "Maio", "Junho", "Julho",
      "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro");
  
  private $nowOn;
  
  public function __construct($nowOn = false) {
    $this->htmlClass = "dateField";
    $this->htmlId = null;
    $this->inputSize = 10;
    $this->nowOn = $nowOn;
  }
  
  public function getHtml($name, $value) {
    return $this->commonHtml($name,$value);
  }

  public function validate($input) {
    return FormFieldDate::validateDate($input, $this->nowOn);
  }
  
  public function clearHtmlClass() {
    $this->htmlClass = "dateField";
  }
  
  public static function validateDate($input, $nowOn = false) {
    if(preg_match('%^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$%', $input) === 1) {
      $pieces = explode('/', $input);
      $day = intval($pieces[0]);
      $month = intval($pieces[1]);
      $year = intval($pieces[2]);
      if($year === 0) {
        return "Ano &eacute; zero.";
      }
      if($month < 1 || $month > 12) {
        return "O m&ecirc;s deve estar entre 1 e 12. Foi dado \"<span class='userInput'>${month}</span>\".";
      }
      $monthDays = (($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0) ? 
                   FormFieldDate::$leapYearsMonths[$month] :
                   FormFieldDate::$nonLeapYearsMonths[$month];
      if($day > $monthDays || $day < 1) {
        $monthName = FormFieldDate::$monthNames[$month];
        return "O dia deve estar entre 1 e ${monthDays} para o m&ecirc;s ${monthName} de ${year}. Foi dado \"<span class='userInput'>${day}</span>\".";
      }
      else if($nowOn) {
        $now = new DateTime("now");
        $diff = $now->diff(FormFieldDate::toDateTime($input));
        if($diff->invert === 1) {
          return "Data deve vir depois da data de agora.";
        }
      }
      return true;
    }
    else {
      return "A data deve estar no formato <em>dd/mm/aaaa</em>. Foi dado \"<span class='userInput'>${input}</span>\".";
    }
  }
  
  /**
   * Retorna um array com (dia, mes, ano).
   * @param type $date
   */
  public static function splitDate($date) {
    $datePieces = explode("/", $date);
    return array(intval($datePieces[0]), intval($datePieces[1]), intval($datePieces[2]));
  }
  
  /**
   * Retorna um DateTime a partir do $date.
   */
  public static function toDateTime($date) {
  	$pieces = FormFieldDate::splitDate($date);
  	$year = $pieces[2];
  	$month = $pieces[1];
  	$day = $pieces[0];
  	return new DateTime("${year}-${month}-${day}T0:0:0", new DateTimeZone("America/Sao_Paulo"));

  	return $dt;
  }
  
}
